package com.xiaoyu.lanling.feature.friend.data

import `in`.srain.cube.request.FailData
import `in`.srain.cube.request.JsonData
import `in`.srain.cube.request.RequestHandler
import `in`.srain.cube.views.list.PagedListDataModelWithRequestTag
import com.xiaoyu.base.net.RequestCreator
import com.xiaoyu.lanling.common.config.HttpConfig
import com.xiaoyu.lanling.event.friend.FriendListEvent
import com.xiaoyu.lanling.feature.friend.model.FriendItem

open class FriendListData<ItemType, RequestType> : PagedListDataModelWithRequestTag<FriendItem, Any>() {

    private val requestTag = Any()

    override fun doQueryData() {
        RequestCreator.create<FriendListEvent>(FriendListEvent::class.java)
                .setRequestUrl(getRequestUrl())
                .appendQueryDataTo(listPageInfo)
                .setRequestHandler(object : RequestHandler<FriendListEvent, JsonData> {
                    override fun processOriginData(originData: JsonData): FriendListEvent {
                        val rawData = originData.optJson("data")
                        val list = mutableListOf<FriendItem>()

                        val rawList = rawData.optJson("list").toList()
                        val isFirstPage = listPageInfo.isFirstPage
                        val preLen = if (isFirstPage) 0 else listPageInfo.dataList.size
                        for ((i, item) in rawList.withIndex()) {
                            list.add(FriendItem(i + preLen, item))
                        }
                        updateResult(rawData, list)
                        return FriendListEvent(requestTag, isFirstPage)
                    }

                    override fun onRequestFail(failData: FailData) {
                        unlockOnRequestFail()
                        FriendListEvent(requestTag, true).fail().post()
                    }

                    override fun onRequestFinish(event: FriendListEvent) {
                        event.post()
                    }
                })
                .enqueue()
    }

    override fun getRequestTag(): Any {
        return requestTag
    }

    open fun getRequestUrl(): String {
        return HttpConfig.LANLING_FRIEND_LIST
    }
}
